<?php

namespace App\Http\Middleware;

use Closure;
use App\Services\Admin\ActionLog\ActionLog as AdminLog;

class ActionLog
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $response = $next($request);

        if (isset($response->original['code'])) {
            $message = isset($response->original['msg']) ? $response->original['msg'] : [];
            if ($response->original['code'] == 0) {
                $this->log(1, $response->original['code'], $message);
            } else if ($response->original['code'] == 3) {
                //登录失败暂时不记录
//                $this->log(3);
                return response()->json($response->original);
            } else {
                $this->log(0, $response->original['code'], $message);
            }
        } else {
            $this->log(0);
        }

        return $response;
    }

    /**
     * 写入日志
     */
    private function log($error = 1, $code = 0, $message = '')
    {
        $action = request()->route();
        if (empty($action)) {
            return null;
        }
        //获取路由别名
        $sign = request()->route()->getName();
        $model = new AdminLog();
        $model->addAdminLog($sign, $error, $code, $message);
    }
}
